package de.tudarmstadt.ukp.muip.fibqdojo.util;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;

public class FrequencyDistribution {

    HashMap<String, Integer> freqDist = new HashMap<String, Integer>();

    public void put(String key) {
        put(key, 1);
    }

    public void put(String key, Integer count) {
        Integer freq = null;
        if ((freq = freqDist.get(key)) == null) {
            freqDist.put(key, count);
        } else {
            freq += count;
            freqDist.put(key, freq);
        }
    }

    public Integer getFrequency(String key) {
        Integer freq = null;
        return ((freq = freqDist.get(key)) == null ? 0 : freq);
    }

    public boolean contains(String key) {
        return getFrequency(key) > 0;
    }

    public List<String> getKeys() {
        return new LinkedList<String>(freqDist.keySet());
    }

    public List<String> getKeysDescending() {

        List<StringFreq> pairs = new LinkedList<StringFreq>();
        Iterator<Entry<String, Integer>> iterator = freqDist.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry<String, Integer> next = iterator.next();
            pairs.add(new StringFreq(next.getKey(), next.getValue()));
        }

        Collections.sort(pairs);

        List<String> keys = new LinkedList<String>();
        for (StringFreq sf : pairs) {
            keys.add(sf.string);
        }

        return keys;
    }

    class StringFreq implements Comparable<StringFreq> {
        private final Integer freq;
        private final String string;

        public StringFreq(String string, Integer freq) {
            this.string = string;
            this.freq = freq;
        }

        @Override //descending - highest value first!
        public int compareTo(StringFreq arg0) {
            if (freq < arg0.freq) {
                return 1;
            }
            if (freq > arg0.freq) {
                return -1;
            }
            return 0;
        }

    }

}
